import { $bus } from "~@/bus/busIndex";
import { debounce } from "~@/untils/NslUtils";
import defaultGif from '~@/assets/default.gif';
import { onUnmounted } from "vue";

export type TypeImgItem= {
    dom:HTMLImageElement,
    src:string,
    isHandled:boolean,
}

let imgs:TypeImgItem[]=[];


function setImg(img:TypeImgItem){
    console.log('in setImg');
    img.dom.src=defaultGif;// 先暂时使用着默认图片
    // 处理图片
    // 该图片是否在视口范围内
    const clientHeight=document.documentElement.clientHeight;
    const rect=img.dom.getBoundingClientRect();
    const height=rect.height || 150;
    if(rect.top >=-height && rect.top <=clientHeight && !img.isHandled){
        console.log('in setImg handle');
        console.log('img.src',img.src);
        img.dom.src=img.src;
        img.isHandled=true;
    }
}

function setImgs(){
    imgs=imgs.filter(e=>!e.isHandled)
    imgs.forEach(e=>{
        setImg(e);
    });
}

function handleScorll(){
    setImgs();
}

$bus.on('mainScroll',debounce(handleScorll,50));

const vLoadImageLazy={
    mounted(el:HTMLImageElement,bindings:TypeDirectiveBindings){
        console.log('in mounted');
        
        const img={
            dom:el,
            src:bindings.value,
            isHandled:false
        }
        imgs.push(img);
        setImg(img);
    },

    unmounted(el:HTMLImageElement){
        imgs=imgs.filter(e=>e.dom!==el);
    }
}

export { vLoadImageLazy}


let x:GloTypeObjValueString={
    a:'ba',
    // b:1 error
}

export type TypeDirectiveBindings={
    arg: string,
    modifiers:GloTypeObjValueString,
    value: any /* value of `baz` */,
    oldValue: any /* value of `baz` from previous update */
}